 package com.oanda.blackberry.util;
 
 import com.oanda.blackberry.util.log.Logger;
 import java.io.IOException;
 import net.rim.device.api.crypto.AbstractDigest;
 import net.rim.device.api.crypto.CryptoException;
 import net.rim.device.api.crypto.CryptoOutputStream;
 import net.rim.device.api.crypto.DigestOutputStream;
 import net.rim.device.api.crypto.MD5Digest;
 
 public class MD5Factory
 {
   public static String getDigestAsString(String text)
   {
     try
     {
       return encodeStringMD5(text); } catch (Exception ex) {
     }
     return "";
   }
 
   private static int sampleMD5Digest(byte[] plainText, byte[] digestData)
     throws CryptoException, IOException
   {
     MD5Digest digest = new MD5Digest();
 
     DigestOutputStream digestStream = new DigestOutputStream(digest, null);
 
     digestStream.write(plainText);
 
     digest.getDigest(digestData, 0);
     Logger.log("Dig len: " + String.valueOf(digest.getDigestLength()));
     return digest.getDigestLength();
   }
 
   public static String encodeStringMD5(String s) throws Exception {
     byte[] bytes = s.getBytes();
     MD5Digest digest = new MD5Digest();
     digest.update(bytes, 0, bytes.length);
     int length = digest.getDigestLength();
     byte[] md5 = new byte[length];
     digest.getDigest(md5, 0, true);
     return convertToHex(md5);
   }
 
   private static String convertToHex(byte[] data) {
     StringBuffer buf = new StringBuffer();
     for (int i = 0; i < data.length; i++) {
       int halfbyte = data[i] >>> 4 & 0xF;
       int two_halfs = 0;
       do {
         if ((0 <= halfbyte) && (halfbyte <= 9))
           buf.append((char)(48 + halfbyte));
         else {
           buf.append((char)(97 + (halfbyte - 10)));
         }
         halfbyte = data[i] & 0xF;
       }while (two_halfs++ < 1);
     }
     return buf.toString();
   }
}

